/**
 * 
 */
package com.zaprit.common.dao.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

import com.rdo.common.bo.Attachment;
import com.zaprit.common.dao.CommonDao;

/**
 * @author Dell
 */
public class CommonDaoImpl implements CommonDao
{
	private SessionFactory	sessionFactory	= null;

	/**
	 * @param sessionFactory
	 */
	public void setSessionFactory(SessionFactory sessionFactory)
	{
		this.sessionFactory = sessionFactory;
	}

	/**
	 * @param newSession
	 * @return Session
	 */
	private Session getSession(boolean newSession)
	{
		Session session = sessionFactory.getCurrentSession();
		if (newSession || session == null)
		{
			session = sessionFactory.openSession();
		}
		return session;
	}

	public Attachment addAttachment(String userId, Attachment attachment)
	{
		Session session = getSession(false);
		session.save(attachment);
		return attachment;
	}

	public Boolean updateAttachment(String userId, Attachment attachment)
	{
		Session session = getSession(false);
		session.saveOrUpdate(attachment);
		return true;
	}

	public Attachment getAttachment(String userId, String attachmentId)
	{
		Session session = getSession(false);
		Criteria criteria = session.createCriteria(Attachment.class);
		criteria = criteria.add(Restrictions.eq("userId", userId));
		criteria = criteria.add(Restrictions.eq("attachmentId", attachmentId));
		return (Attachment) criteria.list().get(0);
	}

	@SuppressWarnings("unchecked")
	public List<Attachment> getAttachments(String userId, List<String> attachmentIds)
	{
		Session session = getSession(false);
		Criteria criteria = session.createCriteria(Attachment.class);
		criteria = criteria.add(Restrictions.eq("userId", userId));
		criteria = criteria.add(Restrictions.in("attachmentId", attachmentIds));
		return criteria.list();
	}
}
